package com.oscar.ehome.view.pageview;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.oscar.ehome.MainActivity;
import com.oscar.ehome.R;
import com.oscar.ehome.base.AppManager;
import com.oscar.ehome.base.C;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.pagebean.StudyDetialBean;
import com.oscar.ehome.presenter.PagePresenter;
import com.oscar.ehome.provider.gildeimage.GildeUtils;
import com.oscar.ehome.utils.basethem.TintManager;
import com.oscar.ehome.utils.database.DataBaseDAO;
import com.oscar.ehome.utils.dowload.dowload.DownloadManager;
import com.oscar.ehome.utils.dowload.dowload.OnDownload;
import com.oscar.ehome.utils.dowload.entity.FileInfo;
import com.oscar.ehome.utils.dowload.progressbar.RoundProgressBar;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.Player;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.utils.util.makeTime;
import com.oscar.ehome.utils.view.progressview.ProgressFrameLayout;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.pageview.view.StudyDetialView;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by oscar
 * author: MengWanhe
 * date: On 2017/7/10
 * 音频播放
 */

public class FrequencyActivity extends BasesActivity<StudyDetialView, PagePresenter> implements StudyDetialView, ProgressFrameLayout.AgainRequestListener {

    /**
     * 返回
     */
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    /**
     * 返回
     */
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /**
     * 音频图片
     */
    @BindView(R.id.freqency_img)
    ImageView freqencyImg;
    /**
     * 回退
     */
    @BindView(R.id.freqency_back_img)
    ImageView freqencyBackImg;
    /**
     * 播放
     */
    @BindView(R.id.freqency_start_img)
    ImageView freqencyStartImg;
    /**
     * 快进
     */
    @BindView(R.id.freqency_speed_img)
    ImageView freqencySpeedImg;
    /**
     * 进度
     */
    @BindView(R.id.qr_pro_pro)
    SeekBar qrProPro;
    /**
     * 标题
     */
    @BindView(R.id.frequen_title)
    TextView frequenTitle;
    /**
     * 作者
     */
    @BindView(R.id.frequen_author)
    TextView frequenAuthor;
    /**
     * 时间
     */
    @BindView(R.id.frequen_time)
    TextView frequenTime;
    /**
     * 下载
     */
    static ImageView frequenDownload;
    /**
     * 内容
     */
    @BindView(R.id.frequen_content)
    TextView frequenContent;
    /**
     * 进度
     */
    static RoundProgressBar freRoundProgressBar;
    /**
     * title布局
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;

    @BindView(R.id.frequens_fragment)
    FrameLayout frequensFragment;

    @BindView(R.id.frequen_fragment)
    ProgressFrameLayout frequenFragment;
    /**
     * 时间
     */
    @BindView(R.id.musicstart_time)
    TextView musicstartTime;
    /**
     * 时间
     */
    @BindView(R.id.musicstart_end)
    TextView musicstartEnd;
    @BindView(R.id.home_tv_num)
    TextView title_tv_right;
    private Player player;
    PagePresenter pagePresenter;

    public int play = 0;
    public String id = "",type = "";
    public String token = "";

    /**
     * 下载的文件详情
     */
    public FileInfo info;

    public String videoUrl = "";//下载地址
    public String fileName = "";//文件名字
    public static String ids = "";//文件ID
    public static String frequen_id = "";//文件ID
    public int dowload = 0;//下载状态
    public String localPath = "";//文件存放路径
    String imgdata = "";//存入数据库的封面图
    String title = "";//存入数据库的标题
    private TimeCount timeCount;
    String startime = "";//开始时间
    String endtime = "";//结束时间
    String time = "";//秒数
    int fin = 0;//是否关闭页面

    DataBaseDAO dataBaseDAO;//数据库

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_frequen);
        ButterKnife.bind(this);
        initView();
        setColor();
        initData();
    }

    /**
     * 设置颜色
     */
    public void setColor() {
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(FrequencyActivity.this).getSystemConfig().getColor()));
        TintManager.setTint(frequenDownload, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
        TintManager.setTint(freqencyBackImg, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
        TintManager.setTint(freqencyStartImg, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
        TintManager.setTint(freqencySpeedImg, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
    }
    /**
     * 倒计时
     */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长,和计时的时间间隔
        }

        @Override
        public void onFinish() {//计时完毕时触发
            title_tv_right.setText("完成");
            title_tv_right.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            title_tv_right.setClickable(false);
            title_tv_right.setText("完成("+millisUntilFinished / 1000 + "秒)");
        }
    }

    /**
     * 初始化
     */
    public void initView() {
        freRoundProgressBar = (RoundProgressBar) findViewById(R.id.fre_roundProgressBar);
        frequenDownload = (ImageView) findViewById(R.id.frequen_download);
        Intent in = getIntent();
        if (in.getStringExtra("type") != null && in.getStringExtra("type").equals("qiangzhi")) {
            type = in.getStringExtra("type");
            titleImgBack.setVisibility(View.GONE);
            title_tv_right.setVisibility(View.VISIBLE);
            timeCount = new TimeCount(60000, 1000);
            timeCount.start();
        } else {
            title_tv_right.setVisibility(View.GONE);
            titleImgBack.setVisibility(View.VISIBLE);
            titleImgBack.setImageResource(R.mipmap.fanhui);
        }
        titleTopbar.setText("音频");
        id = getIntent().getStringExtra("id");
        ids = id;
        token = SystemConfigFactory.getInstance(FrequencyActivity.this).getSystemConfig().getToken();
        startime = makeTime.mtime();

        dataBaseDAO = new DataBaseDAO(FrequencyActivity.this);

        freRoundProgressBar.setVisibility(View.GONE);
       // frequenDownload.setVisibility(View.VISIBLE);
        localPath = CommonUtils.getSDCardRootPath(FrequencyActivity.this) + C.video;// 文件存储路径，sd卡路径

        frequenFragment.setAgainRequestListener(this);
    }

    /**
     * 未开始下载的状态
     */
    public void undowload() {
        if (CommonUtils.GetVideoFileName(CommonUtils.getSDCardRootPath(FrequencyActivity.this) + C.video + fileName)) {// 已下载
            dowload = 1;
            frequenDownload.setImageResource(R.mipmap.duigou);
            frequenDownload.setEnabled(false);
            TintManager.setTint(frequenDownload, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
        } else {
            // 未下载
            dowload = 0;
        }
        if (CommonUtils.isFrec == 1) {
            if (frequen_id.equals(ids)) {
                dowload = 3;
             //   freRoundProgressBar.setVisibility(View.VISIBLE);
                frequenDownload.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 加载数据
     */
    public void initData() {
        pagePresenter.getStudyDetial(token, id);
        showLoading();


    }

    /**
     * 加载数据
     */
    public void saveData() {
        fin = 2;
        time = makeTime.getDistanceTime(Long.parseLong(startime), Long.parseLong(endtime));
        pagePresenter.saveLearn(token, id, startime, endtime, time);
    }

    @OnClick({R.id.title_layout_left,R.id.home_tv_num, R.id.frequen_download, R.id.freqency_back_img, R.id.freqency_start_img, R.id.freqency_speed_img, R.id.fre_roundProgressBar})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.home_tv_num:
                if(title_tv_right.getText().equals("完成")){
                    if(dowload==4){
                        dowload_file();
                    }
                    if(player!=null){

                        player.stop();
                        endtime = makeTime.mtime();
                        saveData();
                    }else{
                        Intent intent;
                        intent = new Intent(FrequencyActivity.this, MainActivity.class);
                        intent.putExtra("intent", 1);
                        startActivity(intent);
                        finish();
                    }
                }else{
                    ToastUtil.show(FrequencyActivity.this, "请倒计时结束后点击退出");
                }
                break;
            case R.id.title_layout_left://返回
                if(dowload==4){
                    dowload_file();
                }
                if(player!=null){

                    player.stop();
                    endtime = makeTime.mtime();
                    saveData();
                }else{

               finish();
                }


                break;
            case R.id.frequen_download://下载
                switch (dowload) {
                    case 0://未下载
//                        if (CommonUtils.isPdf == 1 || CommonUtils.isVideo == 1) {
//                            ToastUtil.show(FrequencyActivity.this, R.string.dowloading);
//                        } else {
//                            dowload_file();
//                        }
                        dowload_file();
                        break;
                    case 1://已下载
                        ToastUtil.show(FrequencyActivity.this, R.string.dowload_file);
                        break;
                    case 3://正在下载，点击暂停
                        puseDowload_file();
                        break;
                    case 4://暂停中，点击继续下载
                        dowload_file();
                        break;
                }
                break;
            case R.id.fre_roundProgressBar://暂停
                switch (dowload) {
                    case 1://已下载
                        ToastUtil.show(FrequencyActivity.this, R.string.dowload_file);
                        break;
                    case 3://正在下载，点击暂停
                        puseDowload_file();
                        break;
                    case 4://暂停中，点击继续下载
                        dowload_file();
                        break;
                }
                break;
            case R.id.freqency_back_img://回退
                int pos_back = player.mediaPlayer.getCurrentPosition();
                pos_back -= 5000; // milliseconds
                player.mediaPlayer.seekTo(pos_back);
                break;
            case R.id.freqency_start_img://播放
                if (play == 0) {//播放
                    startMusic();
                    if (dowload == 0) {
                        dowload_file();
                    }
                } else if (play == 1) {//暂停
                    play = 2;
                    player.pause();
                    freqencyStartImg.setImageResource(R.mipmap.bofang);
                } else if (play == 2) {//继续
                    play = 1;
                    player.play();
                    freqencyStartImg.setImageResource(R.mipmap.zanting);
                    TintManager.setTint(freqencyStartImg, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
                }

                break;
            case R.id.freqency_speed_img://快进
                int pos = player.mediaPlayer.getCurrentPosition();
                pos += 5000; // milliseconds
                player.mediaPlayer.seekTo(pos);
                break;
        }
    }

    @Override
    public void getstudyDetail(StudyDetialBean result) {
        dismissLoading();
        if (result != null) {
            frequenFragment.stopRefresh();
            frequensFragment.setVisibility(View.VISIBLE);

            title = result.getTitle();
            frequenTitle.setText(result.getTitle());
            frequenAuthor.setText(result.getCreateBy().getName());
            frequenTime.setText(result.getUpdateDate());
            frequenContent.setText(result.getRemarks());
            imgdata = C.qiniu_ip + result.getSmallImg();
//            GildeUtils.imgLoadPic(FrequencyActivity.this, imgdata, freqencyImg, "net");
            GildeUtils.loadUrlImages(imgdata, freqencyImg, FrequencyActivity.this);
            videoUrl = C.qiniu_ip + result.getMediaFile();//"http://abv.cn/music/光辉岁月.mp3"
            player = new Player(qrProPro);
            qrProPro.setOnSeekBarChangeListener(new SeekBarChangeEvent());
            fileName = result.getMediaFile();
            try {
                if (CommonUtils.GetVideoFileName(CommonUtils.getSDCardRootPath(FrequencyActivity.this) + C.video + fileName)) {// 已下载
                    player.mediaPlayer.setDataSource(CommonUtils.getSDCardRootPath(FrequencyActivity.this) + C.video + fileName);
                    player.mediaPlayer.prepare();
                    musicstartTime.setText(formatTime(0));
                    musicstartEnd.setText(formatTime(player.mediaPlayer.getDuration()));
                    player.mediaPlayer.reset();
                } else {
                    player.mediaPlayer.setDataSource(videoUrl);
                    player.mediaPlayer.prepare();
                    musicstartTime.setText(formatTime(0));
                    musicstartEnd.setText(formatTime(player.mediaPlayer.getDuration()));
                    player.mediaPlayer.reset();
                }


                }catch(Exception e){

                }

            undowload();
        }
    }

    public void startMusic() {
        play = 1;
        if (dowload == 1) {//本地播放
            player.PlayMusic(CommonUtils.getSDCardRootPath(FrequencyActivity.this) + C.video + fileName);
        } else {//在线播放
            new Thread(new Runnable() {
                @Override
                public void run() {
                    player.playUrl(videoUrl);
                }
            }).start();
        }
        freqencyStartImg.setImageResource(R.mipmap.zanting);
        TintManager.setTint(freqencyStartImg, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
    }

    @Override
    public void saveLearn(String result) {
        if (fin == 2) {
            if(type!=null&&type.equals("qiangzhi")){
                Intent intent;
                intent = new Intent(FrequencyActivity.this, MainActivity.class);
                intent.putExtra("intent", 1);
                startActivity(intent);
                finish();
            }else{
                finish();
            }

        }
    }

    @Override
    public void erroy() {
        dismissLoading();
        frequenFragment.setNoResult();
        frequenFragment.setVisibility(View.VISIBLE);
        frequensFragment.setVisibility(View.GONE);
        ToastUtil.show(FrequencyActivity.this, getString(R.string.erry));
        if (fin == 2) {
            finish();
        }
    }

    @Override
    public void erry(String result) {
        dismissLoading();
        frequenFragment.setNoResult();
        frequenFragment.setVisibility(View.VISIBLE);
        frequensFragment.setVisibility(View.GONE);
        Toast.makeText(FrequencyActivity.this, result, Toast.LENGTH_SHORT).show();
        if (result.contains("过期")) {
            getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(FrequencyActivity.this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(FrequencyActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    /**
     * 下载文件的方法
     */
    public void dowload_file() {
        // 下载
        int info_id = 1;
      //  freRoundProgressBar.setVisibility(View.VISIBLE);
        frequenDownload.setVisibility(View.GONE);

        info = new FileInfo(info_id, videoUrl, fileName, 0, 0);
        final OnDownloadImpl impl = new OnDownloadImpl(freRoundProgressBar, 0);
        DownloadManager.instance(FrequencyActivity.this).startDownload(info.getUrl(), localPath, fileName, impl,
                ids, freRoundProgressBar); // 开始下载
//        ToastUtil.show(FrequencyActivity.this, "开始下载");

        dowload = 3;
    }

    /**
     * 暂停文件的方法
     */
    public void puseDowload_file() {
        dowload = 4;
        int info_id = 1;
        info = new FileInfo(info_id, videoUrl, 0, 0);
        DownloadManager.instance(FrequencyActivity.this).pauseDownload(info.getUrl());
        freRoundProgressBar.setVisibility(View.GONE);
      //  frequenDownload.setVisibility(View.VISIBLE);
        frequenDownload.setImageResource(R.mipmap.zanting);
        TintManager.setTint(frequenDownload, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
    }

    @Override
    public void againRequest() {

    }

    /**
     * 下载回调监听类
     */
    class OnDownloadImpl implements OnDownload {
        public RoundProgressBar pb; // 进度条
        public int position; // 列表位置

        public OnDownloadImpl(RoundProgressBar pb, int posision) {
            this.pb = pb;
            this.position = posision;
        }

        /**
         * 下载中
         */
        @Override
        public void onDownloading(String retUrl, int finished, String bookid, RoundProgressBar pb) {
            frequen_id = bookid;
            if (ids.equals(bookid)) {
                if (dowload == 3) {// 下载中
                  //  freRoundProgressBar.setVisibility(View.VISIBLE);
                    frequenDownload.setVisibility(View.GONE);
                    CommonUtils.isFrec = 1;
                    freRoundProgressBar.setProgress(finished);
                } else if (dowload == 4) {// 暂停
                    // 缓存的暂停的id和此文件的id相同的话点击此按钮直接继续下载,同时移除缓存的此文件id
                    freRoundProgressBar.setVisibility(View.GONE);
                  //  frequenDownload.setVisibility(View.VISIBLE);
                }
            }
        }

        /**
         * 下载完成
         */
        @Override
        public void onDownloadFinished(File downloadFile, int isfinshed) {
            ToastUtil.show(FrequencyActivity.this, "下载完成");
            freRoundProgressBar.setProgress(100);
            freRoundProgressBar.setVisibility(View.GONE);
          //  frequenDownload.setVisibility(View.VISIBLE);
            frequenDownload.setImageResource(R.mipmap.duigou);
            frequenDownload.setEnabled(false);
            TintManager.setTint(frequenDownload, Color.parseColor(SystemConfigFactory.getInstance(FrequencyActivity.this).getSystemConfig().getColor()));

            String sizes = CommonUtils.getFileOrFilesSize(localPath + fileName, 3);
            Log.e("5652525", "initView: "+localPath + fileName);
            //插入数据库
            if (dowload != 1) {
                Map<String, Object> datas = new HashMap<String, Object>();// 存储用户反馈信息
                datas.put("title", title);
                datas.put("imgdata", imgdata);
                datas.put("size", sizes);
                datas.put("filename", fileName);
                datas.put("learnType", "audio/mp3");
                datas.put("ids", id);
                dataBaseDAO.insert("fileDownload", datas);
            }

            dowload = 1;
            CommonUtils.isFrec = 0;
        }

        /**
         * 是否连接网络
         */
        @Override
        public void onNetwork(boolean flag) {// 判断是否有网络
            // TODO Auto-generated method stub
            if (!flag) {// 无网络时
                // 暂停下载
                puseDowload_file();
            } else {// 暂停中 ，开始下载
                dowload_file();
            }
        }

        @Override
        public void onStrartDownloading(String url, String bookid) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onErroy(String bookid) {
            // TODO Auto-generated method stub
            if (ids.equals(bookid)) {
                ToastUtil.show(FrequencyActivity.this, "下载失败");
                freRoundProgressBar.setVisibility(View.GONE);
               // frequenDownload.setVisibility(View.VISIBLE);
                dowload = 0;
            }
        }
    }

    private String formatTime(long time) {
        return CommonUtils.formatTime("mm:ss", time);
    }

    class SeekBarChangeEvent implements SeekBar.OnSeekBarChangeListener {
        int progress;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            // 原本是(progress/seekBar.getMax())*player.mediaPlayer.getDuration()
            this.progress = progress * player.mediaPlayer.getDuration()
                    / seekBar.getMax();
            int starttime = player.mediaPlayer.getCurrentPosition();
            int endtime = player.mediaPlayer.getDuration();
            if (!musicstartEnd.getText().toString().trim().equals(endtime)) {
                musicstartEnd.setText(formatTime(endtime));
            }
            musicstartTime.setText(formatTime(starttime));
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // seekTo()的参数是相对与影片时间的数字，而不是与seekBar.getMax()相对的数字
            player.mediaPlayer.seekTo(progress);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.stop();
        }
    }

    @Override
    protected PagePresenter createPresenter() {
        pagePresenter = new PagePresenter(this);
        return pagePresenter;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(type.equals("qiangzhi")){
                AppManager appManager = AppManager.getAppManager();
                appManager.finishAllActivity();
                finish();
            }else {
                endtime = makeTime.mtime();
                if (dowload == 4) {
                    dowload_file();
                }
                if (videoUrl != null && !"".equals(videoUrl)) {
                    saveData();
                } else {
                    finish();
                }
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
